package com.borqsprocessmanager.wight;

import android.app.PendingIntent;
import android.app.admin.DevicePolicyManager;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

import com.borqsprocessmanager.R;
import com.borqsprocessmanager.receiver.AdminReceiver;

public class ScreenOffWidget extends AppWidgetProvider {

    private final String CLICK_NAME_ACTION = "click_name_action";

    DevicePolicyManager policyManager;
    ComponentName componentName;

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {

        RemoteViews rv = new RemoteViews(context.getPackageName(),
                R.layout.widget_main);
        Intent intentClick = new Intent(CLICK_NAME_ACTION);
        intentClick.setClass(context, ScreenOffWidget.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                intentClick, 0);
        rv.setOnClickPendingIntent(R.id.imageView1, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetIds, rv);
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        super.onReceive(context, intent);
        if (intent.getAction().equals(CLICK_NAME_ACTION)) {
            mylock(context);
        }
    }

    private void mylock(Context context) {
        // 获取设备管理服务
        policyManager = (DevicePolicyManager) context
                .getSystemService(Context.DEVICE_POLICY_SERVICE);

        // AdminReceiver 继承自 DeviceAdminReceiver
        componentName = new ComponentName(context, AdminReceiver.class);
        boolean active = policyManager.isAdminActive(componentName);

        if (!active) {// 若无权限
            activeManage();// 去获得权限
            policyManager.lockNow();// 并锁屏
        }
        if (active) {
            policyManager.lockNow();// 直接锁屏
        }
    }

    private void activeManage() {
        // 启动设备管理(隐式Intent) - 在AndroidManifest.xml中设定相应过滤器
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);

        // 权限列表
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);

        // 描述(additional explanation)
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                "------ 其他描述 ------");

        // startActivityForResult(intent, 0);
    }

}
